<?php

class Adept_Response_Http extends Adept_Response_Abstract
{

    protected $redirected = false;
    protected $headerRedirect = true;

    protected $content = '';
    protected $capture = true;

    static protected $instance;

    public function __construct()
    {
    }

    static public function getInstance()
    {
        if (!isset(self::$instance)) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    public function clear()
    {
        $this->content = '';
    }

    public function flush()
    {
        if ($this->capture) {
            echo $this->content;
            $this->content = '';
        }
        flush();
    }

    /**
     * Send http response header
     *
     * @param string $text
     */
    public function sendHeader($text)
    {
        @header($text);
    }

    public function setCookie($key, $value, $expires = null, $path = null, $domain = null, $secure = null)
    {
        setcookie($key, $value, $expires, $path, $domain, $secure);
    }

    /**
     * Send redirect header
     *
     * @param string $url Target URL
     */
    public function redirect($url, $headerRedirect = null)
    {
        if (is_null($headerRedirect)) {
            $headerRedirect = $this->headerRedirect;
        }

        if ($this->redirected) {
            throw new Adept_Exception('Cannot redirect twice');
        }

        if ($this->headerRedirect) {
            $this->sendHeader('Location: ' . $url);
        } else {
            echo '<html><head>';
            echo '<meta http-equiv="refresh" content="0; url=' . $url . '">';
            echo '</head><body></body></html>';
            flush();
        }
        $this->redirected = true;
    }

    public function redirectToReferer($defaultUrl = '/', $headerRedirect = null) 
    {
        if (isset($_SERVER['HTTP_REFERER']) && !empty($_SERVER['HTTP_REFERER'])) {
            $url = $_SERVER['HTTP_REFERER'];    
        } else {
            $url = $defaultUrl;
        }
        $this->redirect($url, $headerRedirect);
    }	
    
    /**
     * Return true if redirect headed was sent.
     *
     * @return bool
     */
    public function isRedirected()
    {
        return $this->redirected;
    }

    /**
     * Append text to output buffer
     * 
     * @param string $text
     */
    public function write($text)
    {
        if (!$this->capture) {
            echo $text;
        } else {
            $this->content .= $text;
        }
    }

    public function getContent()
    {
        return $this->content;
    }

    public function isCapture() {
        return $this->capture;
    }

    public function setCapture($capture) {
        $this->capture = $capture;
    }

}
